<?php

namespace App\Admin\Controllers;

use App\Models\Org;
use App\Models\UserPermission;
use App\Models\UserRole;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Hash;

class UserController extends AdminController
{
    /**
     * {@inheritdoc}
     */
    protected function title()
    {
        return '系统管理员管理';
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $userModel = config('admin.database.users_model');

        $grid = new Grid(new $userModel());

        $grid->column('name', '姓名')->style('min-width:100px;');
        $grid->column('username', '用户名')->style('min-width:100px;');
//        $grid->column('org.title', '权限范围')->style('min-width:100px;');
        $grid->column('status', '状态')->using(['0' => '禁用', '1' => '启用'], '未知')->dot([
            0 => 'danger',
            1 => 'success',
        ], 'warning')->sortable()->style('min-width:100px;');
        $grid->column('created_at', '创建时间')->style('min-width:100px;');

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            // 去掉查看
            $actions->disableView();
            if ($actions->getKey() == 1) {
                $actions->disableDelete();
            }
        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->batch(function (Grid\Tools\BatchActions $actions) {
                $actions->disableDelete();
            });
        });

        $grid->disableExport();
        $grid->disableRowSelector();


        $grid->filter(function (Grid\Filter $filter) {
            $filter->expand();
            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->like('name', '姓名');
        });

        $grid->setActionClass(Actions::class);

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        $userModel = config('admin.database.users_model');

        $show = new Show($userModel::findOrFail($id));

        $show->field('id', 'ID');
        $show->field('username', trans('admin.username'));
        $show->field('name', trans('admin.name'));
        $show->field('roles', trans('admin.roles'))->as(function ($roles) {
            return $roles->pluck('name');
        })->label();
        $show->field('permissions', trans('admin.permissions'))->as(function ($permission) {
            return $permission->pluck('name');
        })->label();
        $show->field('created_at', trans('admin.created_at'));
        $show->field('updated_at', trans('admin.updated_at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $userModel = config('admin.database.users_model');
        $permissionModel = config('admin.database.permissions_model');
        $roleModel = config('admin.database.roles_model');

        $form = new Form(new $userModel());

        $userTable = config('admin.database.users_table');
        $connection = config('admin.database.connection');

        $form->text('username', '用户名')
            ->creationRules(['required', "unique:{$connection}.{$userTable}"])
            ->updateRules(['required', "unique:{$connection}.{$userTable},username,{{id}}"]);

        $form->text('name', '姓名')->rules('required');
        $form->password('password', trans('admin.password'))->rules('required');
//        $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required')
//            ->default(function ($form) {
//                return $form->model()->password;
//            });
//
//        $form->ignore(['password_confirmation']);

        $form->multipleSelect('roles', trans('admin.roles'))->options($roleModel::all()->pluck('name', 'id'));
        $form->multipleSelect('permissions', trans('admin.permissions'))->options($permissionModel::all()->pluck('name', 'id'));
//        $form->multipleSelect('roles', trans('admin.roles'))->options($roleModel::all()->pluck('name', 'id'))->default([6]);
//        $form->multipleSelect('permissions', trans('admin.permissions'))->options($permissionModel::all()->pluck('name', 'id'))->default([2]);

//        $form->radioButton('type', '权限类型')
//            ->options([
//                1 => '市级',
//                2 => '区县',
//            ])->when(1, function (Form $form) {
//                $form->select('org_id', '权限范围')->options(Org::where('type', 0)->where('id', '=', 1)->pluck('title', 'id'))->default(1)->rules('required');
//            })->when(2, function (Form $form) {
//                $form->select('org_id', '权限范围')->options(Org::where('type', 0)->where('id', '!=', 1)->pluck('title', 'id'))->rules('required');
//            })->default(1)->rules('required');

//        $userOrg = Org::find(Admin::user()->org_id);
//        $form->select('org_id', '权限范围')->options(Org::where('type', 0)->where('path', 'like', $userOrg->path."%")->pluck('title', 'id'))->rules('required');


        $form->radio('status', '状态')->options(['0' => '禁用', '1' => '启用'])->default('1');

        $form->display('created_at', trans('admin.created_at'));

        $form->saving(function (Form $form) {
            if ($form->password && $form->model()->password != $form->password) {
                $form->password = Hash::make($form->password);
            }

        });

//        $form->saved(function (Form $form)use($userModel) {
//
//            $perWhere = [
//                'user_id' => $form->model()->id,
//                'permission_id' => 1,
//            ];
//            !UserPermission::where($perWhere)->exists() && UserPermission::create($perWhere);
//
//            $roleWhere = [
//                'user_id' => $form->model()->id,
//                'role_id' => 1,
//            ];
//            !UserRole::where($roleWhere)->exists() && UserRole::create($roleWhere);
//
//        });

        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();

        });

        $form->tools(function (Form\Tools $tools) {
            // 去掉`列表`按钮
            $tools->disableList();
            // 去掉`删除`按钮
            $tools->disableDelete();
            // 去掉`查看`按钮
            $tools->disableView();
        });

        return $form;
    }
}
